Build an Interactive Joke Generator for Your Website

Faraz

By Faraz -

Learn how to build a random joke generator using HTML, CSS, and JavaScript. Follow our beginner-friendly guide to add laughter to your website today.


Create a Random Joke Generator with HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

Do you want to inject a dose of humor and interactivity into your website? In this comprehensive tutorial, we're going to walk you through the exciting process of building your very own Random Jokes Generator using the dynamic trio of web development technologies: HTML, CSS, and JavaScript. Whether you're a seasoned coder or a complete beginner, you're in the right place. By the end of this guide, you'll have a fully functional joke generator that's sure to bring smiles to your website visitors.

In today's digital landscape, engaging your audience is paramount, and humor is an excellent way to do just that. With the power of HTML, CSS, and JavaScript at your fingertips, you'll be able to create an interactive and entertaining feature that keeps users coming back for more. So, grab your favorite code editor, buckle up, and let's embark on this coding adventure together.

But fear not if you're new to the world of web development! We'll break down each step into manageable pieces, providing clear explanations and code samples along the way. By the time you finish this tutorial, you'll not only have a working jokes generator but also a deeper understanding of how these fundamental web technologies come together to create delightful user experiences. Ready to unleash some laughter?

Let's start making an amazing random joke generator using HTML, CSS, and JavaScript step by step.

Join My Telegram Channel to Download the Project Source Code: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our joke generator.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let's break it down step by step:

1. <!DOCTYPE html>: This declaration specifies that the document is an HTML5 document. It is the first line of an HTML document and tells the browser which version of HTML is being used.

2. <html lang="en">: This is the opening tag for the HTML document. It specifies the language of the document as English ("en").

3. <head>: This is the opening tag for the head section of the document. The head section contains meta-information about the document, such as character encoding, viewport settings, and links to external resources like stylesheets and scripts.

  • <meta charset="UTF-8">: This meta tag specifies the character encoding of the document as UTF-8, which is a character encoding standard that supports a wide range of characters from different languages.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: This meta tag is used to set the X-UA-Compatible HTTP header, which instructs Internet Explorer to use the latest rendering engine available. It helps ensure compatibility with older versions of IE.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: This meta tag is used to configure the viewport settings for responsive design. It sets the width of the viewport to the device's width and sets the initial scale to 1.0, which means the web page will be displayed at its actual size on the device.
  • <title>Random Jokes Generator</title>: This sets the title of the web page, which is displayed in the browser's title bar or tab. In this case, the title is "Random Jokes Generator."
  • <link rel="stylesheet" href="styles.css">: This line links an external stylesheet file named "styles.css" to the HTML document. It allows you to apply styles (such as formatting and layout) to the HTML content.

4. <body>: This is the opening tag for the body section of the document. The body section contains the actual content of the web page that is visible to users.

  • <div class="container">: This is a container div element that wraps the content of the web page. It's often used to group related content together for styling and layout purposes.
  • <h3>Random Jokes Generator</h3>: This is an HTML heading element (h3) that displays the text "Random Jokes Generator." It's a subheading for the page.
  • <div id="joke" class="joke">: This is a div element with an id of "joke" and a class of "joke." It represents an area on the page where random jokes will be displayed.
  • <button id="get_joke" class="btn">Get another joke</button>: This is a button element with an id of "get_joke" and a class of "btn." It's used to trigger an action, to retrieve another random joke when clicked.
  • <script src="script.js"></script>: This line includes an external JavaScript file named "script.js." JavaScript is a programming language used to add interactivity and dynamic behavior to web pages. The script file is linked here, suggesting that it contains code that will run in the browser to handle the functionality of the random joke generator.

This is the basic structure of our random joke generator using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the joke generator is in place, the next step is to add styling to the generator using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to style our generator. Let's break down each part of the code and explain its purpose:

1. @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;500&display=swap');

  • This line imports a font family called "Poppins" from Google Fonts. It specifies different font weights (100, 300, 400, and 500) and requests the "swap" display strategy. The "swap" strategy ensures that the text will be displayed with a fallback font while the Poppins font is being loaded from the web. Once the Poppins font is available, it will be used for rendering the text.

2. * { box-sizing: border-box; }

  • This CSS rule applies the box-sizing property with a value of border-box to all HTML elements on the page. It ensures that when you set the width and height of an element, the padding and border are included in those dimensions.

3. body { background-color: #1f1d2b; font-family: 'Poppins', Arial, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }

  • This rule applies styles to the <body> element:
  • It sets the background color of the entire webpage to a dark blueish color (#1f1d2b).
  • It specifies the font family for the text, prioritizing "Poppins" if available, and falling back to Arial and generic sans-serif fonts.
  • It uses Flexbox (display: flex;) to horizontally and vertically center the content within the body.
  • It sets the height of the body to occupy the full viewport height (100vh), ensuring that the content is centered both vertically and horizontally.
  • It removes any default margin around the body.

4. .container { background-color: #ffd791; border-radius: 10px; box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1), 0 6px 6px rgba(0, 0, 0, 0.1); padding: 50px 20px; max-width: 100%; width: 800px; text-align: center; }

  • This rule applies styles to elements with the class "container" (e.g., a container div):
  • It sets the background color to a light yellow color (#ffd791).
  • It rounds the corners of the container with a 10px border-radius.
  • It adds a box shadow for a subtle shadow effect.
  • It provides padding inside the container with 50px on top and bottom and 20px on the left and right.
  • It ensures that the container doesn't exceed 100% of its parent's width.
  • It sets the container's width to a fixed value of 800px.
  • It centers the text inside the container.

5. h3 { margin: 0; letter-spacing: 2px; opacity: 0.5; }

  • This rule applies styles to all <h3> elements on the page:
  • It removes any default margin around <h3> elements.
  • It adds letter-spacing to create space between characters.
  • It reduces the opacity to make the text semi-transparent.

6. .joke { font-size: 30px; line-height: 40px; margin: 50px auto; max-width: 600px; }

  • This rule applies styles to elements with the class "joke":
  • It sets the font size to 30px.
  • It specifies the line height as 40px to control spacing between lines of text.
  • It centers the element horizontally using margin: 50px auto;.
  • It limits the maximum width to 600px.

7. .btn { background-color: #660033; border: 0; border-radius: 10px; box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1), 0 6px 6px rgba(0, 0, 0, 0.1); color: #fff; cursor: pointer; font-size: 16px; padding: 14px 40px; }

  • This rule applies styles to elements with the class "btn":
  • It sets the background color to a dark purplish color (#660033).
  • It removes the border (border: 0) to create a borderless button.
  • It rounds the corners with a 10px border-radius.
  • It adds a box shadow for a subtle shadow effect.
  • It sets the text color to white.
  • It changes the cursor to a pointer on hover.
  • It sets the font size to 16px.
  • It provides padding inside the button with 14px on top and bottom and 40px on the left and right.

8. .btn:active { transform: scale(0.98); }

  • This rule defines the behavior of the button when it is clicked (in the active state):
  • It scales down the button by 2% to create a slight "pressed" effect.

9. .btn:focus { outline: 0; }

  • This rule removes the default focus outline from buttons when they are clicked, making the button visually cleaner when focused.

This will give our random joke generator an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;500&display=swap');

*{
     box-sizing: border-box
}

body {
    background-color: #1f1d2b;
    font-family: 'Poppins', Arial, sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    margin: 0;
}
.container {
    background-color: #ffd791;
    border-radius: 10px;
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1), 0 6px 6px rgba(0,0, 0, 0, 0.1);
    padding: 50px 20px;
    max-width: 100%;
    width: 800px;
    text-align: center;
}
h3 {
  margin: 0;
  letter-spacing: 2px;
  opacity: 0.5;

}
.joke {
    font-size: 30px;
    line-height: 40px;
    margin: 50px auto;
    max-width: 600px;
}

.btn {
  background-color: #660033;
  border: 0;
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1), 0 6px 6px rgba(0,0, 0, 0, 0.1);
  color: #fff;
  cursor: pointer;
  font-size: 16px;
  padding: 14px 40px;
}

.btn:active{
  transform: scale(0.98);
}

.btn:focus {
  outline: 0;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript.

1. It starts by selecting two elements from the HTML document using the document.getElementById method:

  • jokeEl: This represents an HTML element with the id attribute set to "joke." It's presumably a container where a joke will be displayed.
  • get_joke: This represents an HTML element with the id attribute set to "get_joke." It's a button that can be clicked to fetch and display a new joke.

2. It then adds an event listener to the "get_joke" element. When the "get_joke" button is clicked, the generateJoke function will be called.

3. Finally, it immediately calls the generateJoke function once to display an initial joke on the web page.

4. The generateJoke function is defined as an asynchronous function and performs the following steps:

  1. It uses the fetch function to make an HTTP request to the "https://icanhazdadjoke.com/" URL. This URL is a joke API that provides random dad jokes.
  2. In the request, it specifies that it expects JSON data by setting the 'Accept' header to 'application/json'.
  3. It waits for the response from the API using await.
  4. Once the response is received, it parses the JSON data from the response using await jokeRes.json(). The resulting joke variable contains the joke data.
  5. It updates the HTML content of the jokeEl element with the joke retrieved from the API using jokeEl.innerHTML = joke.joke. This means the joke text will be displayed inside the HTML element with the "joke" ID, effectively showing the dad jokes on the web page.

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

const jokeEl = document.getElementById('joke')
const get_joke = document.getElementById('get_joke');

get_joke.addEventListener('click', generateJoke);
generateJoke();

async function generateJoke(){
    const jokeRes = await fetch('https://icanhazdadjoke.com/', {
        headers: {
            'Accept': 'application/json'
        }
    });

    const joke = await jokeRes.json();

    jokeEl.innerHTML = joke.joke;
}

Final Output:

Create a Random Joke Generator with HTML, CSS, and JavaScript.gif

Conclusion:

In conclusion, you've journeyed through the exciting world of web development and emerged with a fully functional Random Jokes Generator using HTML, CSS, and JavaScript. We hope this tutorial has not only equipped you with a fun feature for your website but also empowered you with valuable skills in coding and user experience design.

Remember, the potential for customization and expansion is limitless. You can enhance your generator with additional features, polish the user interface, or even integrate it into your existing website seamlessly. The choice is yours, and creativity knows no bounds in the world of web development.

As you continue on your coding adventures, keep experimenting, learning, and pushing the boundaries of what's possible. Don't hesitate to share your hilarious creations with the world, and always keep the laughter rolling. Happy coding, and may your website bring joy and amusement to all who visit it!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺